package leetcode;

import java.util.LinkedList;
import java.util.Queue;

public class Leetcode662 {
    public int widthOfBinaryTree(TreeNode root) {
        if(root==null){
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<>();
        LinkedList<Integer> list = new LinkedList<>();
        q.offer(root);
        list.add(1);
        int max = 1;
        while(!q.isEmpty()){
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode tmp = q.poll();
                Integer index = list.removeFirst();
                if(tmp.left!=null){
                    q.offer(tmp.left);
                    list.add(index*2);
                }
                if(tmp.right!=null){
                    q.offer(tmp.right);
                    list.add(index*2+1);
                }
            }
            if(list.size()>=2) {
                max = Math.max(max, list.getLast() - list.getFirst() + 1);
            }
        }
        return max;
    }
}
